import { BufferAttribute, BufferGeometry, Color } from "three";

export const createCloudGeometry = (params: {
  color: string;
  endColor: string;
  count: number;
  branch: number;
  radius: number;
  rotateScale: number;
}): BufferGeometry => {
  const centerColor = new Color(params.color);
  const endColor = new Color(params.endColor);
  const buffergeometry = new BufferGeometry();
  const pointPosition = new Float32Array(params.count * 3);
  const pointColor = new Float32Array(params.count * 3);

  for (let i = 0; i <= params.count; i++) {
    const pointBranch = (i % params.branch) * ((Math.PI * 2) / params.branch);
    const distance = params.radius * Math.random() * Math.pow(Math.random(), 3);
    const current = i * 3;

    // 随机偏移
    const randomX = Math.pow(Math.random() * 2 - 1, 3);
    const randomY = Math.pow(Math.random() * 2 - 1, 3);
    const randomZ = Math.pow(Math.random() * 2 - 1, 3);

    // 计算星星位置
    pointPosition[current] =
      Math.cos(pointBranch + params.rotateScale * distance) * distance +
      randomX;
    pointPosition[current + 1] =
      Math.sin(pointBranch + params.rotateScale * distance) * distance +
      randomY;
    pointPosition[current + 2] = 0 + randomZ;

    const mixColor = centerColor.clone();
    mixColor.lerp(endColor, distance / params.radius);
    pointColor[current] = mixColor.r;
    pointColor[current + 1] = mixColor.g;
    pointColor[current + 2] = mixColor.b;
  }

  buffergeometry.setAttribute(
    "position",
    new BufferAttribute(pointPosition, 3),
  );

  buffergeometry.setAttribute("color", new BufferAttribute(pointColor, 3));

  return buffergeometry;
};
